package com.fly.controller;

import com.fly.bean.Role;
import com.fly.bean.SystemPropertiesValue;
import com.fly.bean.UserLog;
import com.fly.bean.Users;
import com.fly.service.UserManageService;
import com.fly.util.Md5Util;
import com.fly.util.Msg;
import com.fly.util.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/userManage")
public class UserManageController {

    @Resource
    private UserManageService userManageService;

    /**
     * 分页显示查询到的用户日志信息
     * @param page
     * @return
     */
    @RequestMapping("/showUserLog")
    @ResponseBody
    public Msg showUserLogByGetAllUserLog(Page page){
        Integer totalCount = userManageService.selectNumberByAllUserLog();

        //分页对象中设置总数量为查询的数量
        page.setCount(totalCount);
        //用户日志信息
        List<UserLog> userLogList = userManageService.selectAllUserLog(page);

        if (userLogList.size() > 0){
            return Msg.success().add("count",page.getCount()).add("userLogList",userLogList);
        }else{
            return Msg.fail();
        }
    }

    /**
     * 分页显示用户的日志信息通过用户筛选的时间
     * @param page
     * @param startTime
     * @param endTime
     * @return
     */
    @RequestMapping("/showUserLogBySelectDate")
    @ResponseBody
    public Msg showUserLogBySelectDate(Page page,String startTime,String endTime){
        Integer totalCount = userManageService.selectNumberByAllUserLogBySelectDate();

        //分页对象中设置总数量为查询的数量
        page.setCount(totalCount);
        //用户日志信息
        List<UserLog> userLogList = userManageService.selectAllUserLogBySelectDate(page,startTime,endTime);

        if (userLogList.size() > 0){
            return Msg.success().add("count",page.getCount()).add("userLogList",userLogList);
        }else{
            return Msg.fail();
        }
    }

    /**
     * 查询所有的用户信息分页显示
     * 分别查出了最后操作时间，用户状态信息，用户信息
     * @return
     */
    @RequestMapping("/showAllUsers")
    @ResponseBody
    public Msg selectAllUsers(Page page){
        //查询用户的数量
        Integer totalCount = userManageService.selectUsersNumber();
        //分页对象中设置总数量为查询的数量
        page.setCount(totalCount);
        //查询所有的用户名
        String[] allUserName = userManageService.selectUserName(page);
        //最后操作时间
        String[] lastLoginTimes = new String[allUserName.length];

        //循环查询用户的最后操作时间
        for (int i = 0;i<allUserName.length;i++){
            //循环查询取值
            lastLoginTimes[i] = userManageService.selectLastTimeByUserName(allUserName[i]);
//            System.out.println(lastLoginTimes[i]);
        }
        //查询用户状态信息根据用户的userId
        String[] userStates = userManageService.selectSysProValueNameByUserId(page);
        //得到所有的用户信息
        List<Users> usersList = userManageService.selectAllUsers(page);

        if (usersList.size() > 0){
            return Msg.success().add("count",page.getCount()).add("usersList",usersList).add("lastLoginTimes",lastLoginTimes).add("userStates",userStates);
        }else{
            return Msg.fail();
        }
    }

    /**
     * 通过条件查询所有的用户信息分页显示
     * @param page
     * @param userName
     * @param sysProValueName
     * @return
     */
    @RequestMapping("/selectAllUsersByUserNameAndSysProValueName")
    @ResponseBody
    public Msg selectAllUsersByUserNameAndSysProValueName(Page page,String userName,String sysProValueName){

        String newUserName = "%" + userName + "%";
        //查询用户的数量
        Integer totalCount = userManageService.selectUsersNumberByUserNameAndSysProValueName(newUserName,sysProValueName);
        //分页对象中设置总数量为查询的数量
        page.setCount(totalCount);

        //查询用户状态信息根据用户的userId
        String[] userStates = userManageService.selectSysProValueNameByUserIdAndUserNameAndSysProValueName(newUserName,sysProValueName,page);
        //查询用户状态信息根据sysProValueName
        Integer userState = userManageService.selectUserStateBySysProValueName(sysProValueName);
        //查询所有的用户名
        String[] allUserName = userManageService.selectUserNameByUserState(userState,page);

        String[] lastLoginTimes = new String[allUserName.length];
        //循环查询用户的最后操作时间
        for (int i = 0;i<allUserName.length;i++){
            //循环查询取值
            lastLoginTimes[i] = userManageService.selectLastTimeByUserName(allUserName[i]);
        }

        //得到所有的用户信息
        List<Users> usersList = userManageService.selectAllUsersByUserNameAndSysProValueName(page,newUserName,sysProValueName);

        if (usersList.size() > 0){
            return Msg.success().add("count",page.getCount()).add("usersList",usersList).add("lastLoginTimes",lastLoginTimes).add("userStates",userStates);
        }else{
            return Msg.fail();
        }
    }

    /**
     * 查看用户是否存在
     * @param userName
     * @return
     */
    @RequestMapping("/selectUserNameExists")
    @ResponseBody
    public Msg selectUserNameExists(String userName){
        String result = userManageService.selectUserNameExists(userName);

        if (result != null){
            return Msg.fail();
        }else{
            return Msg.success();
        }
    }

    /**
     * 添加用户信息
     * @param userName
     * @param userPwd
     * @param roleName
     * @param joinDate
     * @param leavingDate
     * @param sysProValueName
     * @return
     */
    @RequestMapping("/addUserMessage")
    @ResponseBody
    public Msg addUserMessage(String userName, String userPwd,String roleName,Date joinDate,Date leavingDate,String sysProValueName){
        String userNameExists = userManageService.selectUserNameExists(userName);

        if(userNameExists != null){
            return Msg.fail();
        }else{
            //查询用户状态信息根据sysProValueName
            Integer userState = userManageService.selectUserStateBySysProValueName(sysProValueName);

            //查询角色ID根据角色名称
            Integer roleId = userManageService.selectRoleIdByRoleName(roleName);

            //创建用户对象添加用户信息作为参数传参
            Users user = new Users();
            user.setUserPwd(userPwd);
            user.setUserName(userName);

            //md5加密生成密码
            String newPwd = Md5Util.setDBPwd(user.getUserPwd());

            user.setUserPwd(newPwd);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            user.setJoinDate(joinDate);
            user.setLeavingDate(leavingDate);

            //系统资源对应值对象
            SystemPropertiesValue systemPropertiesValue = new SystemPropertiesValue();
            systemPropertiesValue.setId(userState);
            //角色对象
            Role role = new Role();
            role.setRoleId(roleId);
            //用户添加
            user.setRole(role);
            user.setSystemPropertiesValue(systemPropertiesValue);

            //添加用户信息
            Integer result = userManageService.addUserMessage(user);

            if (result > 0){
                //创建日志对象
                UserLog userLog = new UserLog();
                //操作对象
                userLog.setUser(user);

                //创建用户登录的时间
                Date date = new Date();
                //操作信息
                userLog.setUserLogOperationInformation("用户" + user.getUserName() + "在" + date + "被添加");
                //操作时间
                userLog.setUserLogOperationDate(date);
                //添加日志信息
                userManageService.addUserLog(userLog);

                return Msg.success();
            }else{
                return Msg.fail();
            }
        }
    }

    /**
     * 修改用户信息
     * @param userId
     * @param userName
     * @param roleName
     * @param joinDate
     * @param leavingDate
     * @param sysProValueName
     * @return
     */
    @RequestMapping("/modifyUserMessage")
    @ResponseBody
    public Msg modifyUserMessage(Integer userId,String userName,String roleName,String joinDate,String leavingDate,String sysProValueName){
        //判断用户名是否重复
        String resultUserName = userManageService.selectUserNameExists(userName);

        //根据用户Id查询用户名称
        String selectUserName = userManageService.selectUserNameByUserId(userId);

        if (resultUserName != null && !selectUserName.equals(resultUserName)){
            return Msg.fail();
        }else{
            //查询用户状态信息根据sysProValueName
            Integer userState = userManageService.selectUserStateBySysProValueName(sysProValueName);
            //系统资源对应值对象
            SystemPropertiesValue systemPropertiesValue = new SystemPropertiesValue();
            systemPropertiesValue.setId(userState);

            //查询角色ID根据角色名称
            Integer roleId = userManageService.selectRoleIdByRoleName(roleName);
            //角色对象
            Role role = new Role();
            role.setRoleId(roleId);

            //创建用户对象修改用户信息作为参数传参
            Users user = new Users();
            user.setUserId(userId);
            user.setUserName(userName);

            //md5加密生成密码
//        String newPwd = Md5Util.setDBPwd(user.getUserPwd());
//        user.setUserPwd(newPwd);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                user.setJoinDate(sdf.parse(joinDate));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            try {
                user.setLeavingDate(sdf.parse(leavingDate));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //用户添加
            user.setRole(role);
            user.setSystemPropertiesValue(systemPropertiesValue);

            //修改用户信息
            Integer result = userManageService.modifyUserMessageByUserId(user);

            if (result > 0){
                //创建日志对象
                UserLog userLog = new UserLog();
                //操作对象
                userLog.setUser(user);

                //创建用户登录的时间
                Date date = new Date();
                //操作信息
                userLog.setUserLogOperationInformation("用户" + user.getUserName() + "在" + date + "被修改");
                //操作时间
                userLog.setUserLogOperationDate(date);
                //添加日志信息
                userManageService.addUserLog(userLog);

                return Msg.success();
            }else{
                return Msg.fail();
            }
        }
    }

    /**
     * 删除用户信息
     * @param userId
     * @return
     */
    @RequestMapping("/deleteUserMessage")
    @ResponseBody
    public Msg deleteUserMessage(Integer userId){
        //先根据id获取用户信息不然是先删了，在获取就会报空指针异常
        Users user = userManageService.selectUserByUserId(userId);

        //根据用户Id查询角色Id
        Integer roleId = userManageService.selectRoleIdByUserId(userId);
        //根据角色Id查询角色名称
        String roleName = userManageService.selectRoleNameByRoleId(roleId);
        //当角色名称为超级管理员是该用户不能被删除
        if ("超级管理员".equals(roleName)){
            return Msg.fail();
        }else{
            Integer result = userManageService.deleteUserMessage(userId);

            if (result > 0){
                //创建日志对象
                UserLog userLog = new UserLog();
                //操作对象
                userLog.setUser(user);

                //创建用户登录的时间
                Date date = new Date();
                //操作信息
                userLog.setUserLogOperationInformation("用户" + user.getUserName() + "在" + date + "被删除");
                //操作时间
                userLog.setUserLogOperationDate(date);
                //添加日志信息
                userManageService.addUserLog(userLog);

                return Msg.success();
            }else {
                return Msg.fail();
            }
        }
    }

    /**
     * 修改用户状态通过userId
     * 先通过sysProValueName查询出id(对应与userState)
     * @param userId
     * @return
     */
    @RequestMapping("/modifyUserState")
    @ResponseBody
    public Msg modifyUserState(Integer userId,String sysProValueName){

        //通过sysProValueName查询出id(对应与userState)
        Integer userState = userManageService.selectUserStateBySysProValueName(sysProValueName);

        //修改用户状态通过userId
        Integer result = userManageService.modifyUserState(userState,userId);

        if (result > 0 ){
            //创建用户对象
            Users user = new Users();
            //创建日志对象
            UserLog userLog = new UserLog();
            //操作对象
            userLog.setUser(user);

            //创建用户登录的时间
            Date date = new Date();
            //操作信息
            userLog.setUserLogOperationInformation("用户" + user.getUserName() + "在" + date + "被修改了用户状态信息");
            //操作时间
            userLog.setUserLogOperationDate(date);
            //添加日志信息
            userManageService.addUserLog(userLog);

            return Msg.success();
        }else {
            return Msg.fail();
        }
    }
}
